package cn.tedu.crm.permission.service.impl;

import cn.tedu.crm.permission.pojo.entity.Permission;
import cn.tedu.crm.permission.pojo.vo.MenuTreeVO;
import cn.tedu.crm.permission.pojo.vo.PermissionVO;
import cn.tedu.crm.permission.service.PermissionService;
import cn.tedu.crm.permission.mapper.PermissionMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static org.apache.poi.sl.usermodel.PresetColor.Menu;

/**
* @author tedu
* @description 针对表【permission(权限表)】的数据库操作Service实现
* @createDate 2025-03-13 19:35:35
*/
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements PermissionService {
    @Autowired
    PermissionMapper permissionMapper;

    @Override
    public List<MenuTreeVO> selectPermission() {
        List<Permission> permissions = this.list(
                new LambdaQueryWrapper<Permission>()
                        .orderByAsc(Permission::getParentId)
        );
        List<MenuTreeVO> allMenus = new ArrayList<>();
        for (Permission permission : permissions) {
            MenuTreeVO menuTreeVO = new MenuTreeVO();
            BeanUtils.copyProperties(permission, menuTreeVO);
            allMenus.add(menuTreeVO);
        }



        // 使用Map优化查找效率
        Map<Long, List<MenuTreeVO>> parentMap = allMenus.stream()
                .collect(Collectors.groupingBy(MenuTreeVO::getParentId));

        allMenus.forEach(menu ->
                menu.setChildren(parentMap.getOrDefault(menu.getId(), Collections.emptyList()))
        );

        return parentMap.getOrDefault(0L, Collections.emptyList());
    }
}




